import Vue from 'vue'

import Cookies from 'js-cookie'
import Element from 'element-ui'

// global css
import 'normalize.css/normalize.css'
import './assets/styles/element-variables.scss'
import './assets/styles/index.scss'

import './assets/icons' // icon
import './router/index' //

import App from './App'
import store from './store'
import router from './router/routers'
import Pagination from './components/Pagination'
import permission from './components/Permission'
import ContextMenu from './components/ContextMenu'
import './assets/iconfont/iconfont.css' // icon
import VueAMap from 'vue-amap'
Vue.use(VueAMap)
VueAMap.initAMapApiLoader({
  key: '90654984c9eaf9ffd3350f4a5441e2bf',
  plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar',
  'AMap.MapType', 'AMap.Geolocation', 'AMap.Geocoder', 'AMap.AMapManager', 'AMap.Marker'],
  uiVersion: '1.0', // ui库版本，不配置不加载,
  v: '1.4.4'
})

// 全局方法挂载

// 全局组件挂载
Vue.component('Pagination', Pagination)
Vue.component('ContextMenu', ContextMenu)

Vue.use(permission)
Vue.use(Element, {
  size: Cookies.get('size') || 'large' // set element-ui default size
})

Vue.directive('preventReClick', {
  inserted(el, binding) {
    el.addEventListener('click', () => {
      if (!el.disabled) {
        el.disabled = true
        setTimeout(() => {
          el.disabled = false
        }, binding.value || 2000)
      }
    })
  }
})

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})

Vue.prototype.$bus = new Vue()

function $$newParent() {
  let parent = arguments[0]
  let func = arguments[1]
  let para = []
  for (let i = 2; i < arguments.length; i++) {
    para.push(arguments[i])
  }
  return new Promise(resolve => {
    let checkParent = idx => {
      if (parent.$parent && idx < 20) {
        parent = parent.$parent
        if (parent[func] !== undefined) {
          if (typeof (parent[func]) === 'function') {
            resolve(parent[func](...para))
          } else {
            if (arguments.length >= 3) { // 判定是赋值
              parent[func] = arguments[2]
              resolve(parent[func])
            } else { // 判定是读值
              resolve(parent[func])
            }
          }
        } else {
          checkParent(idx + 1)
        }
      } else {
        console.log('未找到：' + func)
        resolve(undefined)
      }
    }
    checkParent(0)
  }, reject => {})
}

Vue.prototype.$$parent = $$newParent

function $checkPermission(permission) {
  if (!permission) {
    return true
  }
  const userPower = store.getters && store.getters.userInfo.UserPower
  // console.log('userPower.' + JSON.stringify(userPower))
  return userPower.includes(permission)
}

Vue.prototype.$checkPermission = $checkPermission
